package com.xzmzhp.security;

import com.xzmzhp.dao.people.PersonnelMapper;
import com.xzmzhp.service.power.MenuService;
import com.xzmzhp.utils.StringUtils;
import com.xzmzhp.vo.personnel.PersonnelVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 王源(xm)
 * @Date: 2020/12/3 21:27
 * @Description: 登录逻辑类
 */
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(MyUserDetailsService.class);

    /**
     * 注入数据库操作类
     */
    @Autowired
    private PersonnelMapper personnelMapper;

    @Autowired
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String studentId) throws UsernameNotFoundException {
        //调用personnelMapper方法，根据用户查询数据库
        PersonnelVo personnelVo = personnelMapper.findByStudentId(studentId);
        //判断用户是否存在
        if (StringUtils.isNull(personnelVo)) {
            log.info("登录用户：{} 不存在.", personnelVo.getPersonnelName());
            throw new UsernameNotFoundException("用户不存在");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        // 声明用户授权
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(personnelVo.getCompetenceName());
        grantedAuthorities.add(grantedAuthority);
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(personnelVo);
        return loginUser;
    }

    public UserDetails createLoginUser(PersonnelVo personnelVo) {
        return new LoginUser(personnelVo, menuService.selectMenuByCompetence(personnelVo));
    }
}
